package cn.initcap.concurrency.concurrency.singleton;

import cn.initcap.concurrency.annoations.Recomend;
import cn.initcap.concurrency.annoations.ThreadSafe;

/**
 * 懒汉模式{双重同步锁，使用volatile来限制指令重排的发生，线程安全}
 * <p>
 * 运行步骤：
 * 1.memory = allocate()分配对象的内存空间
 * 2.ctorInstance() 初始化对象
 * 3.instance = memory 设置instance指向刚分配的内存
 *
 * @author initcap
 * @date Created in 2018/6/14 PM12:26.
 */
@ThreadSafe
@Recomend
public class SingletonDoubleCheckLockVolatile {

    /**
     * 单例对象 volatile + 双重检测机制
     */
    private static volatile SingletonDoubleCheckLockVolatile instance = null;

    /**
     * 私有构造函数
     */
    private SingletonDoubleCheckLockVolatile() {

    }

    /**
     * 静态的工厂方法
     */
    public static SingletonDoubleCheckLockVolatile getInstance() {
        // 双重检测机制
        if (instance == null) {
            //同步锁
            synchronized (SingletonDoubleCheckLockVolatile.class) {
                if (instance == null) {
                    instance = new SingletonDoubleCheckLockVolatile();
                }
            }
        }
        return instance;
    }

}
